<template>
  <div class="employee">
    <div class="top">
      <div class="top_left">
        <selectTool
          :colmuns="headerConfig"
          :model-form="configData"
          @onFormChange="getEmployeeList"
        ></selectTool>
      </div>
      <div class="right">
        <el-button type="primary" @click="openDialog">添加员工</el-button>
      </div>
    </div>
    <div class="content">
      <newTable
        :table-config="tableConfig"
        :table-data="tableList"
        :option-list="tableOptionList"
        :options="true"
        @clickBtn="go"
        @changeStatus="changeStatus"
      ></newTable>
    </div>
    <div class="footer">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        @prev-click="prev"
        @change="sizeChange"
        @next-click="next"
      />
    </div>
  </div>

  <el-dialog v-model="dialogVisible" :title="dialogTitle" width="650">
    <div style="padding: 10px">
      <el-form
        label-width="100px"
        :model="addData"
        :rules="addDataRules"
        ref="addDataRef"
        v-if="addType !== 'role'"
      >
        <el-form-item label="员工名称" prop="name">
          <el-input
            v-model="addData.name"
            placeholder="请输入员工名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="账号" prop="username">
          <el-input
            v-model="addData.username"
            placeholder="请输入账号"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="addData.password"
            type="password"
            show-password
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addData.email" placeholder="请输入邮箱"></el-input>
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input
            v-model="addData.age"
            placeholder="请输入员工年龄"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否为管理员" prop="admin">
          <el-switch
            v-model="addData.admin"
            class="ml-2"
            style="
              --el-switch-on-color: #13ce66;
              --el-switch-off-color: #ff4949;
            "
          />
        </el-form-item>
        <el-form-item label="所属部门" prop="departmentId">
          <el-select
            v-model="addData.departmentId"
            placeholder="请选择所属部门"
            style="width: 240px"
          >
            <el-option
              v-for="item in departmentList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属角色" prop="roleId">
          <el-select
            v-model="addData.roleId"
            placeholder="请选择角色"
            style="width: 240px"
          >
            <el-option
              v-for="item in roleList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="add(addDataRef, roleValue)">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import {
  getEmployeeListApi,
  addEmployeeApi,
  deleteEmployeeApi,
  // getEmployeeAuthorityApi,
  changeEmployeeAdminApi,
  getRoleByIdApi,
} from "@/api/employeeApi";
import { getDepartmentListApi } from "@/api/departmentApi";
import { getRoleListApi } from "@/api/roleApi";
import { onMounted, reactive, ref } from "vue";
import selectTool from "@/components/selectTool/index.vue";
import newTable from "@/components/newTable/index.vue";
import {
  headerConfig,
  configData,
  tableConfig,
  tableList,
  tableOptionList,
  addDataRules,
  addDataRef,
  roleList,
  roleValue,
} from "./config";
import { ElMessage, type FormInstance } from "element-plus";
import { de } from "element-plus/es/locales.mjs";

/**
 * @description 添加部门弹窗
 */
const dialogVisible = ref(false);

const dialogTitle = ref("添加员工");

const addType = ref("");

/**
 * @description 打开添加部门弹窗
 */
const openDialog = () => {
  dialogVisible.value = true;
  dialogTitle.value = "添加员工";
  addData.id = "";
  addData.name = "";
  addType.value = "add";
  roleValue.value = "";
  if (addDataRef.value) {
    addDataRef.value.resetFields();
  }
};

/**
 * @description 表格操作
 */
const go = (item: any, option: String) => {
  console.log(item, option);
  switch (option) {
    case "delete":
      del(item.row.id);
      break;
    case "edit":
      editDsepartment(item.row);
      break;
    case "role":
      roleEmployee(item.row);
      break;
    default:
      break;
  }
};

/**
 * @description 添加部门数据
 */
const addData = reactive({
  id: "",
  name: "",
  username: "",
  password: "",
  email: "",
  age: "",
  admin: "",
  departmentId: "",
  roleId: "",
});

/**
 * @description 添加员工
 */
const add = async (formEl: FormInstance | undefined, data?: any) => {
  getEmployeeRole();
  console.log("添加员工", addData, roleValue.value);
  if (!formEl) return;
  if (addType.value === "role") {
    dialogVisible.value = false;
    return;
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      const newAddData = {
        employee: {
          ...addData,
          dept: { id: addData.departmentId },
        },
        roleIds: [addData.roleId],
      };
      addEmployeeApi(newAddData).then((res: any) => {
        dialogVisible.value = false;
        getEmployeeList();
        formEl.resetFields();
        if (addType.value === "edit") {
          ElMessage.success("修改成功");
        } else {
          ElMessage.success("添加成功");
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

/**
 * @description 编辑员工
 */
const editDsepartment = (item: any) => {
  // console.log("编辑1", item);
  addDataRef.value?.resetFields();
  dialogTitle.value = "编辑员工";
  addType.value = "edit";
  dialogVisible.value = true;
  addData.id = item.id;
  addData.name = item.name;
  addData.username = item.username;
  addData.password = item.password;
  addData.email = item.email;
  addData.age = item.age;
  addData.admin = item.admin;
  addData.departmentId = item.dept.id;
  getEmployeeRoleById(item.id);
};

const roleEmployee = (item: any) => {
  dialogTitle.value = "查看角色";
  dialogVisible.value = true;
  addType.value = "role";
  addData.id = item.id;
  addData.name = item.name;
  getEmployeeRoleById(item.id);
};

/**
 * @description 删除员工
 */
const del = (id: number) => {
  // console.log("删除", id);
  deleteEmployeeApi(id).then((res: any) => {
    // console.log(res);
    getEmployeeList();
    ElMessage.success("删除成功");
  });
};

/**
 * @description 获取员工权限
 */
const getEmployeeRole = () => {
  getRoleListApi({ pageNum: 1, pageSize: -1 }).then((res: any) => {
    // console.log("测试", res);
    roleList.value = res.data.list.map((item: any) => {
      return {
        value: item.id,
        label: item.name,
      };
    });
    // console.log("WQE", roleList.value);
  });
};

/**
 * @description 获取员工权限
 */
const getEmployeeRoleById = (id: number) => {
  // getEmployeeRole();
  getRoleByIdApi(id).then((res: any) => {
    // console.log("测试", res.data[0].id);
    addData.roleId = res.data[0].id;
  });
};

/**
 * @description 修改员工管理员状态
 */
const changeStatus = (item: any) => {
  console.log("changeStatus", item.admin);
  changeEmployeeAdminApi({ id: item.id, isAdmin: item.admin }).then(
    (res: any) => {
      // console.log(res);
      getEmployeeList();
      ElMessage.success("修改成功");
    }
  );
};

/**
 * 员工总条数
 */
const total = ref(0);

const pageNum = ref(1);

const pageSize = ref(10);

/**
 * @description 获取员工列表
 */
const getEmployeeList = () => {
  getEmployeeListApi({
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    keyword: configData.value.name,
    deptName: configData.value.deptName,
  }).then((res: any) => {
    console.log(res);
    tableList.value = res.data.list.map((i: any) => {
      return {
        ...i,
        deptName: i.dept.name,
      };
    });
    total.value = res.data.total;
  });
};

/**
 * @description 上一页
 */
const prev = () => {
  console.log("上一页");
  getEmployeeListApi({
    pageNum: pageNum.value - 1,
    pageSize: 10,
  }).then((res: any) => {
    // console.log(res);
    tableList.value = res.data.list.map((i: any) => {
      return {
        ...i,
        deptName: i.dept.name,
      };
    });
    total.value = res.data.total;
  });
};

/**
 * @description 下一页
 */
const next = () => {
  console.log("下一页");
  getEmployeeListApi({
    pageNum: pageNum.value + 1,
    pageSize: 10,
  }).then((res: any) => {
    // console.log(res);
    tableList.value = res.data.list.map((i: any) => {
      return {
        ...i,
        deptName: i.dept.name,
      };
    });
    total.value = res.data.total;
  });
};

/**
 * @description 每页显示条数
 */
const sizeChange = (val: number) => {
  console.log(val);
  pageNum.value = val;
  getEmployeeListApi({
    pageNum: pageNum.value,
    pageSize: 10,
  }).then((res: any) => {
    // console.log(res);
    tableList.value = res.data.list.map((i: any) => {
      return {
        ...i,
        deptName: i.dept.name,
      };
    });
    total.value = res.data.total;
  });
};

const departmentList = ref([]) as any;

/**
 * @description 获取所有部门
 */
const getDepartmentList = () => {
  getDepartmentListApi({ pageNum: 1, pageSize: -1 }).then((res: any) => {
    console.log("部门", res);

    departmentList.value = res.data.list.map((item: any) => {
      return {
        label: item.name,
        value: item.id,
      };
    });
  });
};

onMounted(() => {
  getEmployeeList();
  getDepartmentList();
  getEmployeeRole();
});
</script>

<style>
.employee {
  display: flex;
  flex-direction: column;
  height: 100%;
  border-radius: 15px;
}

.top {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
  padding: 0 20px 0 0;
  background-color: rgb(255, 255, 255);
  border-radius: 15px;
  box-shadow: 1px 1px 5px 1px rgba(0, 0, 0, 0.1); /* 阴影 */
  margin-bottom: 10px;
  flex: 0 0 auto;
}

.content {
  height: 100%;
  display: flex;
  background-color: rgb(255, 255, 255);
  border-radius: 15px;
  box-shadow: 1px 1px 5px 1px rgba(0, 0, 0, 0.1); /* 阴影 */
  flex: 1 1 auto;
  overflow: auto;
  padding: 10px;
}

.footer {
  display: flex;
  justify-content: center;
  margin-top: 10px;
  background-color: rgb(255, 255, 255);
  border-radius: 15px;
  box-shadow: 1px 1px 5px 1px rgba(0, 0, 0, 0.1); /* 阴影 */
  height: 60px;
  flex: 0 0 auto;
}
</style>
